import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:carousel_slider_plus/carousel_slider_plus.dart';
import 'package:ecy_app_flutter/routes/blind_box/blind_box_list.dart';
import 'package:ecy_app_flutter/routes/blind_box/category_image_selector.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/EcyExchangeMarketPage.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/blind_box_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../model/EcyApiCommonPage.dart';
import '../../../model/EcyApiCommonResponse.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../goods/model/CommodityTop.dart';

class BlindBoxOneChoose extends StatefulWidget {
  const BlindBoxOneChoose({super.key,required this.commodityPageList});
  final List<BlindBoxPageMore> commodityPageList;

  @override
  State<BlindBoxOneChoose> createState() => _BlindBoxOneChooseState();
}

class _BlindBoxOneChooseState extends State<BlindBoxOneChoose> {
  _BlindBoxOneChooseState();

  final RefreshController _refreshControllerFirst = RefreshController(initialRefresh: false);
  final RefreshController _refreshControllerSec = RefreshController(initialRefresh: false);

  int _currentPage = 1;
  bool _hasMore = false;

  final List<int> indexList = List.filled(19, 0);
  final List<CommodityTop> _commodityTopList = [];

  // 新增：模拟图片和已购买数据
  final List<String> imgList = [
    'https://picsum.photos/400/600?image=10',
    'https://picsum.photos/400/600?image=20',
    'https://picsum.photos/400/600?image=30',
    'https://picsum.photos/400/600?image=40',
    'https://picsum.photos/400/600?image=50',
    'https://picsum.photos/400/600?image=10',
    'https://picsum.photos/400/600?image=20',
    'https://picsum.photos/400/600?image=30',
    'https://picsum.photos/400/600?image=40',
    'https://picsum.photos/400/600?image=50',
  ];
  List<bool> isBought = [false, true, false, false, true,false, true, false, false, true]; // 注意：不再final，便于刷新
  int currentIndex = 0;
  final PageController _pageController = PageController();

  @override
  void initState() {
    super.initState();
    _refreshData("");
    fetchBoughtStatus(); // 页面加载时获取已购买状态
  }

  //无数据时下拉刷新
  Future<void> _onRefresh1() async {
    _currentPage = 1;
    await _refreshData("");
    // 重置上拉加载状态
    _refreshControllerFirst.refreshCompleted();
  }

  //下拉刷新
  Future<void> _onRefresh2() async {
    _currentPage = 1;
    await _refreshData("");
    _refreshControllerSec.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading2() async {
    if (_hasMore) {
      _currentPage++;
      await _refreshData("");
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  Future<void> _refreshData(String search) async {
    try {
      Map<String, dynamic> body = {
        "pageIndex": _currentPage,
        "pageSize": 2,
        "search": search,
      };
      var response = await EcyRequestbasemanager().get("/app/api/app/top/top", body);
      if (response != null) {
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<BlindBoxPageMore> commonPage =
              EcyApiCommonPage.fromJson(response["data"], (json) => BlindBoxPageMore.fromJson(json));
          _hasMore = (commonPage.pages ?? 0) > _currentPage;
          _currentPage = commonPage.current ?? 0;
          var commodityPageList = commonPage.records ?? [];
          if (_currentPage == 1) {
            widget.commodityPageList.clear();
          }
          setState(() {
            widget.commodityPageList.addAll(commodityPageList);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取盲抽失败$e");
    }
  }

  // 1. 购买图片接口调用
  Future<void> buyImage(int imageIndex) async {
    // TODO: 替换为真实接口
    // var response = await EcyRequestbasemanager().post(
    //   "/api/buyImage",
    //   {"imageIndex": imageIndex, "userId": "yourUserId"},
    // );
    // if (response['code'] == 200) {
    //   setState(() { isBought[imageIndex] = true; });
    //   ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('购买成功！')));
    // } else {
    //   ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('购买失败，请重试')));
    // }
    // --- 本地模拟 ---
    await Future.delayed(Duration(milliseconds: 500));
    setState(() {
      isBought[imageIndex] = true;
    });
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('购买成功！')));
  }

  // 2. 页面加载时获取已购买状态
  Future<void> fetchBoughtStatus() async {
    // TODO: 替换为真实接口
    // var response = await EcyRequestbasemanager().get(
    //   "/api/getBoughtStatus",
    //   {},
    // );
    // if (response['code'] == 200) {
    //   List<int> boughtIndexes = List<int>.from(response['data']);
    //   setState(() {
    //     for (int i = 0; i < isBought.length; i++) {
    //       isBought[i] = boughtIndexes.contains(i);
    //     }
    //   });
    // }
    // --- 本地模拟 ---
    await Future.delayed(Duration(milliseconds: 500));
    // 假设后端返回图片1和图片4已被买
    List<int> boughtIndexes = [1,4,7,8,9];
    setState(() {
      for (int i = 0; i < isBought.length; i++) {
        isBought[i] = boughtIndexes.contains(i);
      }
    });
  }

  // 切换到下一个可用图片
  void goToNextImage() {
    int next = currentIndex;
    do {
      next = (next + 1) % imgList.length;
    } while (isBought[next] && next != currentIndex);
    setState(() {
      currentIndex = next;
      _pageController.jumpToPage(currentIndex);
    });
  }

  // 切换到上一个可用图片
  void goToPreviousImage() {
    int prev = currentIndex;
    do {
      prev = (prev - 1 + imgList.length) % imgList.length;
    } while (isBought[prev] && prev != currentIndex);
    setState(() {
      currentIndex = prev;
      _pageController.jumpToPage(currentIndex);
    });
  }

  // 左上角位置指示器
  Widget _buildPositionIndicator() {
    int total = imgList.length;
    int itemsPerRow = 3;
    if (total > 9) itemsPerRow = 4;
    int rowCount = (total / itemsPerRow).ceil();

    List<Widget> rows = [];
    for (int row = 0; row < rowCount; row++) {
      int start = row * itemsPerRow;
      int end = (start + itemsPerRow > total) ? total : start + itemsPerRow;
      rows.add(
        Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: List.generate(end - start, (i) {
            int index = start + i;
            bool bought = isBought[index];
            bool selected = currentIndex == index;
            return Padding(
              padding: EdgeInsets.only(right: i < end - start - 1 ? 8 : 0, bottom: 4),
              child: GestureDetector(
                onTap: bought
                    ? null
                    : () {
                        setState(() {
                          currentIndex = index;
                          _pageController.jumpToPage(currentIndex);
                        });
                      },
                child: Container(
                  width: 13,
                  height: 13,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: bought
                        ? Color(0xFFF5F5F5)
                        : (selected ? Color(0xFFEA4B9B) : Color(0x19FF53A9)),
                    // border: Border.all(
                    //   color: selected ? Color(0xFFEA4B9B) : Color(0xFFFF53A9),
                    //   width: selected ? 2 : 1,
                    // ),
                    shape: BoxShape.circle,
                  ),
                  child: Text(
                    "${index + 1}",
                    style: TextStyle(
                      fontSize: 8,
                      color: bought
                          ? Color(0xFFFFFFFF)
                          : (selected ? Colors.white : Colors.white),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ),
            );
          }),
        ),
      );
    }

        return Align(
      alignment: Alignment.centerLeft,
      child: IntrinsicWidth(
        child: Card(
          color: Colors.white,
          elevation: 0,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text("当前位置", style: TextStyle(fontSize: 12, color: Color(0xFF000000))),
                SizedBox(height: 4),
                ...rows,
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0XFFF5F5F5),
      appBar: AppBar(
        title: Text('盲抽选择', style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w700, color: Color(0xFF000000)),),
        centerTitle: true,
        backgroundColor: const Color(0XFFF5F5F5),
        leadingWidth: 50.w,
        scrolledUnderElevation: 0,
        leading: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            EcyRouter.pop(context, "");
          },
          child: Align(
            alignment: Alignment.centerRight,
            child: Image.asset(
              "assets/images/ic_back.png",
              width: 30.w,
            ),
          ),
        ),
        actions: [
          GestureDetector(
              onTap: () {},
              child: Padding(
                padding: EdgeInsets.only(right: 12.w),
                child: Image.asset(
                  'assets/images/kf.png',
                  width: 24.w,
                  height: 24.h,
                ),
              )),
          GestureDetector(
              onTap: () {},
              child: Padding(
                  padding: EdgeInsets.only(right: 16.w),
                  child: Image.asset(
                    'assets/images/share.png',
                    width: 24.w,
                    height: 24.h,
                  )))
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(
              "assets/images/blind_box_bg@2x.png",
            ),
            fit: BoxFit.cover,
          ),
        ),
        child: Stack(
          children: [
            // 主内容
            Column(
              children: [
                // SizedBox(height: 16.h),
                // 位置指示器占位（避免被内容遮挡）
                SizedBox(height: 8),
               CategoryImageSelector(
                commodityList: widget.commodityPageList
                    .expand((e) => e.commoditySkuVoList ?? <BlindBoxDetailMore>[])
                    .toList()
              ),
                // SizedBox(height: 8),
                Padding(
                  padding: EdgeInsets.fromLTRB(16.w, 0, 0, 0), 
                  child: Align(
                          alignment: Alignment.centerLeft, 
                          child: _buildPositionIndicator()
                        )
                ),
                // SizedBox(height: 10),
                // 图片切换区
                SizedBox(
                  height: 300.h,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // 左按钮
                      IconButton(
                        icon: Icon(Icons.arrow_left, size: 32),
                        onPressed: goToPreviousImage,
                      ),
                      // 图片
                      Container(
                        width: 220.w,
                        height: 220.w,
                        child: PageView.builder(
                          physics: NeverScrollableScrollPhysics(),
                          controller: _pageController,
                          itemCount: imgList.length,
                          onPageChanged: (index) {
                            if (!isBought[index]) {
                              setState(() {
                                currentIndex = index;
                              });
                            } else {
                              // 自动跳到下一个可用
                              goToNextImage();
                            }
                          },
                          itemBuilder: (context, index) {
                            return Opacity(
                              opacity: isBought[index] ? 0.3 : 1.0,
                              child: Image.network(
                                imgList[index],
                                fit: BoxFit.cover,
                              ),
                            );
                          },
                        ),
                      ),
                      // 右按钮
                      IconButton(
                        icon: Icon(Icons.arrow_right, size: 32),
                        onPressed: goToNextImage,
                      ),
                    ],
                  ),
                ),
                // Padding(padding: EdgeInsets.only(top: 16.h)),
                _buildButton(),
              ],
            ),
            // 左上角位置指示器
            // Positioned(
            //   top: 16,
            //   left: 16,
            //   child: buildPositionIndicator(),
            // ),
          ],
        ),
      ),
      bottomNavigationBar: GestureDetector(
        onTap: () {
          showModalBottomSheet(
            context: context,
            isScrollControlled: true, // 允许全屏
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
            ),
            builder: (context) => Container(
              height: MediaQuery.of(context).size.height * 0.8,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
              ),
              child: Center(child: EcyExchangeMarketPage()),
            ),
          );
        },
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          height: 82.h,
          child: Column(
            
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              const Icon(CupertinoIcons.chevron_compact_up),
              SizedBox(height: 10.h),
              const Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Text('互换集市'),
                  // Text('我的交换'),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget avatar = Image.asset('assets/images/login_app_icon.png', width: 70.w, height: 70.h, fit: BoxFit.cover);

  Container _buildBoxHead() {
    return Container(
        height: 112.h,
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        decoration: BoxDecoration(
          color: const Color(0xFFFFFFFF), // 背景颜色
          borderRadius: BorderRadius.all(Radius.circular(8.r)), // 圆角边框
        ),
        child: GestureDetector(
            child: SizedBox(
              height: 112.h,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Padding(
                    padding: EdgeInsets.only(
                      left: 16.w,
                    ),
                    child: SizedBox(
                      width: 78.w,
                      height: 78.h,
                      child: DecoratedBox(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4.r), //3像素圆角
                          border: Border.all(
                            color: const Color(0x10EA4B9B),
                            width: 2,
                          ),
                        ),
                        child: Padding(
                          padding: EdgeInsets.all(6.w),
                          child: CachedNetworkImage(
                            width: 78.w,
                            height: 78.h,
                            imageUrl: "",
                            imageBuilder: (context, imageProvider) => Container(
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.all(Radius.circular(8.r)),
                                  image: DecorationImage(image: imageProvider, fit: BoxFit.cover)),
                            ),
                            placeholder: (context, url) => avatar,
                            errorWidget: (context, url, error) => avatar,
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(vertical: 18.h),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            "咒术回战咒术回战咒术回战咒术回",
                            style: TextStyle(
                              fontFamily: "PingFang SC",
                              fontWeight: FontWeight.w700,
                              fontSize: 12.sp,
                              color: const Color(0xFF262626),
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              RichText(
                                  textDirection: TextDirection.ltr,
                                  textAlign: TextAlign.end,
                                  text: TextSpan(children: [
                                    WidgetSpan(
                                      child: Padding(
                                        padding: EdgeInsets.only(right: 5.w),
                                        child: Text(
                                          "￥15.00",
                                          style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontSize: 12.sp,
                                            fontWeight: FontWeight.w700,
                                            color: const Color(0xFFF55F4E),
                                          ),
                                        ),
                                      ),
                                    ),
                                    WidgetSpan(
                                        child: Text(
                                      "/抽",
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontSize: 12.sp,
                                        fontWeight: FontWeight.w500,
                                        color: const Color(0xFF8C8C8C),
                                      ),
                                    )),
                                  ])),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 42.w, // 设置宽度
                    height: 28.h, // 设置高度
                    child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        EcyRouter.pop(context, "");
                      },
                      child: Image.asset(
                        "assets/images/rightArrow.png",
                        width: 24.w,
                        height: 24.h,
                      ),
                    ),
                  )
                ],
              ),
            ),
            onTap: () {
              EcyRouter.push(context, "", {});
            }));
  }
 

  SizedBox _buildBoxBody() {
    // final List<String> imgList = [
    //   'https://picsum.photos/400/600?image=10',
    //   'https://picsum.photos/400/600?image=20',
    //   'https://picsum.photos/400/600?image=30',
    //   'https://picsum.photos/400/600?image=40',
    //   'https://picsum.photos/400/600?image=50',
    // ];
    return SizedBox(
      height: 300.h,
      width: 300.w,
      child: CarouselSlider.builder(
          itemCount: imgList.length,
          options: CarouselOptions(
            aspectRatio:1,
            enlargeCenterPage: true,
            viewportFraction: 1,
          ),
          itemBuilder: (BuildContext context, int itemIndex, int pageViewIndex) {
            var item = imgList[itemIndex];
            return Container(
              // margin: const EdgeInsets.all(5.0),
              child: ClipRRect(
                borderRadius: const BorderRadius.all(Radius.circular(5.0)),
                child: Stack(
                  children: <Widget>[
                    Image.network(
                      item,
                      fit: BoxFit.cover,
                      width: double.infinity,
                      height: 350.h,
                    ),
                    Positioned(
                      bottom: 0.0,
                      left: 0.0,
                      right: 0.0,
                      child: Container(
                        decoration: const BoxDecoration(
                          gradient: LinearGradient(
                            colors: [
                              Color.fromARGB(200, 0, 0, 0),
                              Color.fromARGB(0, 0, 0, 0),
                            ],
                            begin: Alignment.bottomCenter,
                            end: Alignment.topCenter,
                          ),
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
                        child: Text(
                          'No. ${imgList.indexOf(item)} image',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 20.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          }),
    );
  }
  Widget _buildButton() {
    return Container(
        child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              Container(
                width: 140.w, // 设置宽度
                height: 40.h, // 设置高度
                decoration: BoxDecoration(
                  gradient: LinearGradient(colors: [Color(0xFFFF7BBE), Color(0xFFFF3E9F)]),
                  borderRadius: BorderRadius.circular(24),
                ),
                child: TextButton(
                  onPressed: isBought[currentIndex]
                      ? null
                      : () async {
                          await buyImage(currentIndex);
                        },
                  style: TextButton.styleFrom(
                    padding: EdgeInsets.zero,
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
                  ),
                  child: Text(
                    isBought[currentIndex] ? '已售出' : '立即购买',
                    style: TextStyle(
                      fontFamily: "PingFang SC",
                      fontWeight: FontWeight.w700,
                      fontSize: 16.sp,
                      color: const Color(0xFFFFFFFF),
                    ),
                  ),
                ),
              ),
            ],
          )
    );
  }


  @override
  void dispose() {
    _refreshControllerFirst.dispose();
    _refreshControllerSec.dispose();
    super.dispose();
  }
}
